//
//  ExampleHttpResponseParser.swift
//  YD_NetworkModule
//
//  Created by 钟志远 on 2020/3/28.
//  Copyright © 2020 alyadan. All rights reserved.
//

import Foundation
import Alamofire
import RxSwift
import RxCocoa
import SwiftyJSON

public class ExampleRspParser: HTTPRespParserType {
    
    public var responseDealBlock: ((Parameters?) -> Parameters?)?
    public var paramsDealBlock: ((Parameters?) -> Parameters?)?
    
    public func httpRequest(httpMethod: HTTPMethod, url: String, param: Parameters?, baseUrl: URL?, header: HTTPHeaders? = nil) -> Observable<(YDNetworkSuccessResp)> {
        
        return Observable.create({ (dataObserver:AnyObserver) -> Disposable in
            
            if url == "NULL" {
                dataObserver.onError(YDNetworkError.paramError)
                return Disposables.create()
            }
            
            guard let escapedURLString = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let resultUrl = URL(string: escapedURLString, relativeTo: baseUrl ?? URL.init(string: "")) else {
                dataObserver.onError(YDNetworkError.paramError)
                return Disposables.create()
            }
            
            let req = request(resultUrl, method: httpMethod, parameters: param, headers: header).responseJSON { (response) in
                switch response.result{
                case .success(let value):
                    var jsonValue = JSON(value)
                    if let deal = self.responseDealBlock {
                        jsonValue = JSON(deal(jsonValue.dictionaryObject) ?? [:])
                    }
                    guard let  errorCode  = jsonValue["err"].int else {
                        dataObserver.onError(YDNetworkError.responseDataError)
                        return
                    }
                    
                    guard errorCode == 0 else {
                        dataObserver.onError(YDNetworkError.serverError(url: url, param: param,msg: jsonValue["errMsg"].stringValue, code: errorCode))
                        return
                    }
                    
                    guard let data = jsonValue["data"].object as? [String: Any] else {
                        dataObserver.onError(YDNetworkError.responseDataError)
                        return
                    }
                    
                    dataObserver.onNext((data, jsonValue.dictionary))
                    dataObserver.onCompleted()
                case .failure(let err):
                    dataObserver.onError(YDNetworkError.connectError(url: url, param: param, error: err))
                }
                
            }
            
            let dispose = Disposables.create(with: {
                req.cancel()
            })
            
            return dispose
        })
//            .retry(2)
            .share(replay: 1)
        
    }
    
}
